// common/services/network/network_exception.dart
import 'package:dio/dio.dart';

class NetworkException implements Exception {
  final String message;
  final int? code;
  final DioExceptionType? type;
  final dynamic originalError;
  
  NetworkException({
    required this.message,
    this.code,
    this.type,
    this.originalError,
  });
  
  // 从DioException创建NetworkException
  factory NetworkException.fromDioException(DioException dioException) {
    String message;
    int? code = dioException.response?.statusCode;
    
    switch (dioException.type) {
      case DioExceptionType.connectionTimeout:
        message = '连接超时，请检查网络设置';
        break;
      case DioExceptionType.sendTimeout:
        message = '发送超时，请重试';
        break;
      case DioExceptionType.receiveTimeout:
        message = '接收超时，请重试';
        break;
      case DioExceptionType.badResponse:
        message = _handleStatusCode(code);
        break;
      case DioExceptionType.cancel:
        message = '请求已取消';
        break;
      case DioExceptionType.connectionError:
        message = '网络连接失败，请检查网络设置';
        break;
      case DioExceptionType.badCertificate:
        message = '证书验证失败';
        break;
      case DioExceptionType.unknown:
      default:
        message = '网络请求失败，请重试';
        break;
    }
    
    return NetworkException(
      message: message,
      code: code,
      type: dioException.type,
      originalError: dioException,
    );
  }
  
  // 处理HTTP状态码
  static String _handleStatusCode(int? statusCode) {
    switch (statusCode) {
      case 400:
        return '请求参数错误';
      case 401:
        return '未授权，请重新登录';
      case 403:
        return '禁止访问';
      case 404:
        return '请求的资源不存在';
      case 405:
        return '请求方法不允许';
      case 408:
        return '请求超时';
      case 409:
        return '请求冲突';
      case 422:
        return '请求参数验证失败';
      case 429:
        return '请求过于频繁，请稍后重试';
      case 500:
        return '服务器内部错误';
      case 502:
        return '网关错误';
      case 503:
        return '服务暂时不可用';
      case 504:
        return '网关超时';
      default:
        return '网络请求失败 (${statusCode ?? 'Unknown'})';
    }
  }
  
  // 创建自定义异常
  factory NetworkException.custom(String message, {int? code}) {
    return NetworkException(
      message: message,
      code: code,
    );
  }
  
  // 网络不可用异常
  factory NetworkException.noInternet() {
    return NetworkException(
      message: '网络不可用，请检查网络连接',
      code: -1,
    );
  }
  
  // 解析错误异常
  factory NetworkException.parseError() {
    return NetworkException(
      message: '数据解析失败',
      code: -2,
    );
  }
  
  @override
  String toString() {
    return 'NetworkException{message: $message, code: $code, type: $type}';
  }
}
